package com.xzkydz.bluetoothlib;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;

import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;


import com.xzkydz.bluetoothlib.adapter.ParameterAdapter;
import com.xzkydz.bluetoothlib.adapter.PrintAdapter;
import com.xzkydz.bluetoothlib.bean.ItemPaddingBean;
import com.xzkydz.bluetoothlib.bean.PrintBean;
import com.xzkydz.bluetoothlib.bean.Regulation;
import com.xzkydz.bluetoothlib.view.MyButton;

import java.util.ArrayList;
import java.util.List;

import static com.xzkydz.bluetoothlib.bean.PrintBean.PRINT_TYPE;


abstract public class BluetoolthPrintActivity extends AppCompatActivity {

    private AppBarLayout appBarLayout;
    private Toolbar toolbar;
    private Spinner spChoose;
    private CheckBox cbSjdw;
    private CheckBox cbSbbh;
    private CheckBox cbJcry;
    private CheckBox cbCssj;
    private ListView lvBt;
    private ListView lvPar;
    private Switch sw;
    private MyButton pbSearch;
    //private Switch fla;
    private TextView searchHint;

    private ArrayList<PrintBean> mBluetoothDevicesDatas;
    private BluetoothAdapter mBluetoothAdapter;
    public static final int REQUEST_ENABLE_BT = 1;
    private PrintAdapter adapter;
    private ParameterAdapter parameterAdapter = null;
    private int color ;
    private String tittleStr = "打印测试数据";


    /**
     * 通过广播搜索蓝牙设备
     */
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 把搜索的设置添加到集合中
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                //已经匹配的设备
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    addBluetoothDevice(device);

                    //没有匹配的设备
                } else {
                    addBluetoothDevice(device);
                }
                adapter.notifyDataSetChanged();
                //搜索完成
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setViewStatus(false);
            }
        }

        /**
         * 添加数据
         * @param device 蓝牙设置对象
         */
        private void addBluetoothDevice(BluetoothDevice device) {
            for (int i = 0; i < mBluetoothDevicesDatas.size(); i++) {
                if (device.getAddress().equals(mBluetoothDevicesDatas.get(i).getAddress())) {
                    mBluetoothDevicesDatas.remove(i);
                }
            }
            if (device.getBondState() == BluetoothDevice.BOND_BONDED && device.getBluetoothClass().getDeviceClass() == PRINT_TYPE) {
                mBluetoothDevicesDatas.add(0, new PrintBean(device));
            } else {
                mBluetoothDevicesDatas.add(new PrintBean(device));
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setStatus();
        initView();
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);  //决定左上角的图标是否可以点击
        initData();
        blueControl();
        tittleStr = setTittleContent("打印测试数据");
        BluetoolthPrintActivity.this.setTitle(tittleStr);
        color = setTittleColor(R.color.colorPrimary);
        toolbar.setBackgroundColor(getResources().getColor(color));
    }

    private void initView() {
        appBarLayout = (AppBarLayout) findViewById(R.id.appbarlayout);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        spChoose = (Spinner) findViewById(R.id.sp_choose);
        cbSjdw = findViewById(R.id.cb_sjdw);
        cbSbbh = findViewById(R.id.cb_sbbh);
        cbJcry = findViewById(R.id.cb_csry);
        cbCssj = findViewById(R.id.cb_cssj);
        lvBt = findViewById(R.id.lv_bt);
        lvPar = findViewById(R.id.lv_par);
        sw = findViewById(R.id.switch1);
    //    fla = findViewById(R.id.floatingActionButton);
        pbSearch = findViewById(R.id.pb_search);
        searchHint = findViewById(R.id.searchHint);

        cbSjdw.setText(setPublicParametersName().get(0));
        cbSbbh.setText(setPublicParametersName().get(1));
        cbJcry.setText(setPublicParametersName().get(2));
        cbCssj.setText(setPublicParametersName().get(3));
    }

    private void initData() {
        // 左上角点击事件
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 设置方案选择内容
        List<Regulation> regulations = setRegulations();
        List<String> regName = new ArrayList<>();
        for (int i = 0; i < regulations.size(); i++) {
            regName.add(regulations.get(i).getName());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, android.R.id.text1, regName);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spChoose.setAdapter(adapter);
        setListView(BluetoolthPrintActivity.this, setParametersName(), regulations.get(0));

        spChoose.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                setListView(BluetoolthPrintActivity.this, setParametersName(), setRegulations().get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void setListView(Context context, List<String> parNameS, Regulation regulation) {
        parameterAdapter = new ParameterAdapter(context, parNameS, regulation , setItemPadding());
        lvPar.setAdapter(parameterAdapter);
    }

    /**
     * 蓝牙操作
     */
    private void blueControl() {
        mBluetoothDevicesDatas = new ArrayList<>();
        //广播注册
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
        //初始化
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        adapter = new PrintAdapter(this, mBluetoothDevicesDatas);
        lvBt.setAdapter(adapter);
        checkBluetooth();
        addViewListener();
    }


    /**
     * 搜索状态调整
     *
     * @param isSearch 是否开始搜索
     */
    @SuppressLint("RestrictedApi")
    private void setViewStatus(boolean isSearch) {

        if (isSearch) {
           // fla.setVisibility(View.GONE);
            searchHint.setVisibility(View.VISIBLE);
           // pbSearch.setVisibility(View.VISIBLE);
            pbSearch.Searching();
        } else {
          //  fla.setVisibility(View.VISIBLE);
           // pbSearch.setVisibility(View.GONE);
            searchHint.setVisibility(View.GONE);
            pbSearch.Stop();
        }
    }


    /**
     * 添加View的监听
     */
    private void addViewListener() {
        //蓝牙的状态
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    openBluetooth();
                    setViewStatus(true);
                } else {
                    closeBluetooth();
                }
            }
        });
        //重新搜索
        pbSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sw.isChecked()) {
                    searchDevices();
                    setViewStatus(true);
                } else {
                    openBluetooth();
                    setViewStatus(true);
                }
            }
        });
    }


    /**
     * 判断有没有开启蓝牙
     */
    private void checkBluetooth() {
        //没有开启蓝牙
        if (mBluetoothAdapter != null) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 设置蓝牙可见性，最多300秒
                intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);
                startActivityForResult(intent, REQUEST_ENABLE_BT);
                setViewStatus(true);
                //开启蓝牙
            } else {
                searchDevices();
                setViewStatus(true);
                sw.setChecked(true);
            }
        }
    }

    /**
     * 搜索蓝牙设备
     */
    private void searchDevices() {
        mBluetoothDevicesDatas.clear();
        adapter.notifyDataSetChanged();
        //开始搜索蓝牙设备
        mBluetoothAdapter.startDiscovery();
    }

    /**
     * 打开蓝牙
     */
    private void openBluetooth() {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 设置蓝牙可见性，最多300秒
        intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 20);
        startActivityForResult(intent, REQUEST_ENABLE_BT);
    }

    /**
     * 关闭蓝牙
     */
    private void closeBluetooth() {
        mBluetoothAdapter.disable();
    }


    /**
     * 获取打印的内容
     * <p>
     * adapter 中调用
     */
    public String getPrintContent() {
        List<String> tittleList = setParametersData().subList(0, 4);
        List<String> dataList = setParametersData().subList(4, setParametersData().size());
        List<String> unitList = setParametersUnit();
        List<String> nameList = setParametersName();

        String contentStr = "-----Start-----\n\n";
        contentStr += cbSjdw.isChecked() ? cbSjdw.getText().toString()+ ": " + tittleList.get(0) + "\n" : "";
        contentStr += cbSbbh.isChecked() ? cbSbbh.getText().toString() + ": "+ tittleList.get(1) + "\n" : "";
        contentStr += cbJcry.isChecked() ? cbCssj.getText().toString() + ": "+ tittleList.get(2) + "\n" : "";
        contentStr += cbCssj.isChecked() ? cbCssj.getText().toString() + ": "+ tittleList.get(3) + "\n" : "";

        for (int i = 0; i < setParametersName().size(); i++) {
            if (parameterAdapter.getCheckedArry()[i]) {
                contentStr += (nameList.get(i) + ": " + dataList.get(i) + " " + unitList.get(i) + "\n");
            }
        }
        contentStr += "\n\n-----End-----\n\n\n\n";
        return contentStr;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_ENABLE_BT) {
            Log.e("text", "开启蓝牙");
            searchDevices();
            sw.setChecked(true);
            mBluetoothDevicesDatas.clear();
            adapter.notifyDataSetChanged();
        } else if (resultCode == RESULT_CANCELED && requestCode == REQUEST_ENABLE_BT) {
            Log.e("text", "没有开启蓝牙");
            sw.setChecked(false);
            setViewStatus(false);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }


    public void setStatus(){
    }

    // 设置标题
    public String setTittleContent(String name){
        return name;
    }

    // 设置标题颜色
    public int setTittleColor(int color) {
        return color;
    }

    public ItemPaddingBean setItemPadding(){
        ItemPaddingBean bean = new ItemPaddingBean(80,80,5,5);
        return bean;
    }

    public List<String> setPublicParametersName(){
        List<String> ppNamse = new ArrayList<>();
        ppNamse.add("受检单位");
        ppNamse.add("设备编号");
        ppNamse.add("检测人员");
        ppNamse.add("测试时间");
        return ppNamse;
    }

    /**
     * 设置规则
     * @return
     */
    abstract public List<Regulation> setRegulations();

    /**
     * 设置界面参数
     * @return
     */
    abstract public List<String> setParametersName();

    /**
     * 每次打印，需要传入的参数
     * @return
     */
    abstract public List<String> setParametersData();

    /**
     * 参数对应的单位。
     * @return
     */
    abstract public List<String> setParametersUnit();

}
